package edu.nf.ch03.service;

import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.prompt.Prompt;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;

/**
 * @author wangl
 * @date 2025/4/19
 */
@Service
@RequiredArgsConstructor
public class SseChatService {

    private final ChatModel chatModel;

    public SseEmitter chat(String prompt) {
        //创建SSE发射器，设置超时的时间（例如：1分钟）
        SseEmitter emitter = new SseEmitter(60_000L);
        //创建提示词对象
        Prompt p = new Prompt(prompt);
        //构建流式响应
        chatModel.stream(p).subscribe(response -> {
            String token = response.getResult().getOutput().getText();
            if(token != null) {
                //发送sse事件
                try {
                    emitter.send(SseEmitter.event()
                            .data(token)
                            .id(String.valueOf(System.currentTimeMillis()))
                            .build());
                } catch (IOException e) {
                    throw new RuntimeException("Send data error.", e);
                }
            }
        },
        //异常处理
        emitter::completeWithError,
        //完成处理
        emitter::complete);

        //设置sse超时时间
        emitter.onTimeout(emitter::complete);

        return emitter;
    }
}